#!/usr/bin/env python3
# coding:utf-8
import subprocess


def run_cmd_realtime_output(cmd):
    # 调用 subprocess.Popen 来执行命令，使用 stdout=subprocess.PIPE 和 stderr=subprocess.STDOUT 来合并并捕获标准输出和错误输出
    process = subprocess.Popen(
        command,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        universal_newlines=True,
    )

    # 循环读取输出
    for line in iter(process.stdout.readline, ""):
        print("--:",line.strip())

    # 等待进程结束并获取返回码
    return_code = process.wait()
    if return_code != 0:
        print("--:",return_code)


def run_shell_realtime_output(cmd):
    p = subprocess.Popen(
        cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT
    )
    while p.poll() is None:
        line = p.stdout.readline()
        line = line.decode("utf-8").strip()
        if line:
            print(f">: {line}")

    line = p.stdout.read()
    line = line.decode("utf-8").strip()
    if line:
        print(f">: {line}")

    if p.returncode == 0:
        print("Subprogram success")
    else:
        print("Subprogram failed")


def run_shell_realtime_output_v2(cmd):
    p = subprocess.Popen(
        cmd,
        shell=True,
        stdout=subprocess.PIPE,
        stderr=subprocess.STDOUT,
        universal_newlines=True,
    )
    # 循环读取输出
    for line in iter(p.stdout.readline, ""):
        print(line.strip())

    return_code = p.wait()
    if return_code != 0:
        print(f"return code: {return_code}")


if __name__ == "__main__":
    cmd = "ping www.baidu.com -t 10 -c 4"
    run_shell_realtime_output(cmd)
    run_shell_realtime_output_v2(cmd)

    command = ["ping", "www.qq.com", "-t", "10", "-w", "4"]
    run_cmd_realtime_output(command)
